<template>
    <div class="bg">
        <div class="Tkcontent">
            <h2 class="h3">裁判报名</h2>
            <!-- <el-dialog title="裁判员报名" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false"> -->
            <el-form class="TKform" :model="ruleForm" :rules="rules" ref="judgeForm" label-position="left"
                     size="medium">
                <el-form-item prop="raceName" label="赛事名称:">
                    <el-input v-model="raceName" readonly autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="raceDate" label="比赛日期:">
                    <el-input v-model="raceDate" readonly autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="deadDate" label="报名截止日期:">
                    <el-input v-model="deadDate" readonly autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="idcard" label="身份证号:">
                    <el-input id="idcard" @blur="queryInfo" v-model="ruleForm.idcard" autocomplete="off"
                              placeholder="请输入身份证号"></el-input>
                </el-form-item>
                <el-form-item prop="name" label="姓名:">
                    <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入性名"></el-input>
                </el-form-item>
                <el-form-item prop="avatar" label="证件照（免冠正装,竖版小二寸）:">
                    <!-- <el-upload action="http://localhost:9090/file/upload" ref="img" :on-success="handleImgUploadSuccess">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    </el-upload> -->
                    <imgUpload :transfer="getmsg" :imgUrl="imgUrl"></imgUpload>
                </el-form-item>
                <el-form-item prop="sex" label="性别:">
                    <el-select v-model="ruleForm.sex" placeholder="请选择性别" style="width:100%">
                        <el-option v-for="item in sex"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="phone" label="手机:">
                    <el-input v-model="ruleForm.phone" autocomplete="off" placeholder="请输入常用手机号"></el-input>
                </el-form-item>

                <el-form-item prop="representUnit" label="代表单位:">
                    <el-input v-model="ruleForm.representUnit" placeholder="请输入代表单位（所在省份）"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="workUnit" label="工作单位:">
                    <el-input v-model="ruleForm.workUnit" autocomplete="off" placeholder="请输入工作单位"></el-input>
                </el-form-item>
                <el-form-item prop="judgeLevel" label="现裁判等级:">
                    <el-select v-model="ruleForm.judgeLevel" placeholder="请选择裁判等级" @change="updateJudgeLevel()"
                               style="width:100%">
                        <el-option v-for="item in levels"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="passDate" label="现等级通过时间:">
                    <el-date-picker v-model="ruleForm.passDate" type="date" value-format="yyyy-MM-dd"
                                    placeholder="选择日期" :picker-options="pickerOptions" style="width:100%"></el-date-picker>
                </el-form-item>
                <el-form-item prop="latestRecord" label="备注:">
                    <el-input v-model="ruleForm.latestRecord" autocomplete="off"
                              placeholder="请输入最近执裁或复训活动名称及地点（例：裁判长-湖南长沙），没有填无"></el-input>
                </el-form-item>

            </el-form>
            <div class="TKfooter">
                <!--            <el-button @click="dialogFormVisible = false">取 消</el-button>-->
                <el-button type="danger" :disabled="this.linkStatus" @click="save" size="medium">确 定</el-button>
            </div>
            <!-- </el-dialog> -->

        </div>
    </div>
</template>
<script>
    import imgUpload from '../components/imgUpload.vue'

    export default {
        name: "JudgeLink",
        data() {
            return {
                tableData: [],
                total: 0,
                pageNum: 1,
                pageSize: 10,
                name: "",
                form: {},
                dialogFormVisible: false,
                multipleSelection: [],
                user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
                linkStatus: true,
                ruleForm: {
                    name: '',
                    sex: '',
                    idcard: '',
                    phone: '',
                    representUnit: '',
                    workUnit: '',
                    passDate: '',
                    latestRecord: ''
                },
                rules: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                    ],
                    sex: [
                        {required: true, message: '请选择性别', trigger: 'change'}
                    ],
                    idcard: [
                        {required: true, message: '请输入身份证号', trigger: 'blur'},
                        {
                            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '你的身份证格式不正确'
                        }
                    ],
                    phone: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码'}
                    ],
                    representUnit: [
                        {required: true, message: '请输入代表单位', trigger: 'blur'}
                    ],
                    workUnit: [
                        {required: true, message: '请输入工作单位', trigger: 'blur'}
                    ],
                    judgeLevel: [
                        {required: true, message: '请选择裁判等级', trigger: 'change'}
                    ],
                    passDate: [
                        {required: true, message: '请选择日期', trigger: 'change'}
                    ],
                    latestRecord: [
                        {required: true, message: '最近执裁或复训活动名称及地点', trigger: 'blur'}
                    ]
                },
                levels: [
                    {value: '0', label: '国际级'},
                    {value: '1', label: '国家级'},
                    {value: '2', label: '预备国家级'}
                    // {value: '3', label: '二级'},
                    // {value: '4', label: '三级'}
                ],
                sex: [
                    {value: '0', label: '男'},
                    {value: '1', label: '女'},
                ],
                linkId: this.$route.query.linkId,
                raceId: '',
                raceName: '',
                raceDate: '',
                deadDate: '',
                imgData: null,
                imgUrl: '',
                pickerOptions: {
                    disabledDate: (time) => {
                        // 禁用今天之前的日期选择
                        return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000;
                    }
                },
            }
        },
        created() {
            this.load()
            this.linkStatus = false
        },
        // mounted() {
        //     this.checkLinkStatus()
        // },
        components: {imgUpload},
        methods: {
            updateJudgeLevel(val) {
                // this.$set(this.ruleForm, 'judgeLevel', this.ruleForm.judgeLevel)
                // //强制刷新
                this.$forceUpdate()
            },

            /**
             * 校验链接是否过期
             */
            checkLinkStatus() {
                let currentTime = new Date();
                // 设置指定的时间
                let year = this.deadDate.split("-")[0]
                let month = this.deadDate.split("-")[1]
                let day = this.deadDate.split("-")[2]
                let specifiedTime = new Date(year, month - 1, day, 23, 59, 59); // JavaScript中月份从0开始计数，所以month-1
                // 比较两个时间的差值
                if (specifiedTime < currentTime) {
                    this.$alert("该链接已失效，请联系报名人员")
                    this.linkStatus = true
                }
            },
            /**
             * 查询信息
             * @param idcard
             */
            queryInfo() {
                let idcard = this.ruleForm.idcard;
                if(idcard ==="" || idcard === undefined){
                    return false
                }
                const data = {
                    "idcard": idcard,
                    "raceId": this.raceId
                }
                this.request.post("/judge/queryAllJudges", data).then(res => {
                    if (res.code === 200) {
                        this.ruleForm.name = res.data[0].name
                        this.ruleForm.sex = res.data[0].sex
                        this.ruleForm.phone = res.data[0].phone
                        this.ruleForm.avatar = res.data[0].avatar
                        this.ruleForm.representUnit = res.data[0].representUnit
                        this.ruleForm.workUnit = res.data[0].workUnit
                        // this.ruleForm.judgeLevel = res.data[0].judgeLevel
                        this.$set(this.ruleForm, 'judgeLevel', res.data[0].judgeLevel)
                        this.ruleForm.passDate = res.data[0].passDate
                        this.ruleForm.latestRecord = res.data[0].latestRecord
                        this.imgUrl = res.data[0].avatar
                        this.imgData = null
                    }else {
                        this.ruleForm.name = ''
                        this.ruleForm.sex = ''
                        this.ruleForm.phone = ''
                        this.ruleForm.avatar = ''
                        this.ruleForm.representUnit = ''
                        this.ruleForm.workUnit = ''
                        this.$set(this.ruleForm, 'judgeLevel', res.data[0].judgeLevel)
                        this.ruleForm.passDate = ''
                        this.ruleForm.latestRecord = ''
                        this.imgUrl =''
                        this.imgData = null
                    }
                });
            },
            getmsg(img) {
                this.imgUrl = ''
                this.imgData = img

            },
            load() {
                this.request.get("/link/findOne?linkId=" + this.linkId).then(res => {
                    if (res.code === 200) {
                        this.raceName = res.data.raceName + "("+res.data.raceStation+")"
                        this.raceDate = res.data.raceDate
                        this.raceId = res.data.raceId
                        this.deadDate = res.data.deadDate
                        this.checkLinkStatus()

                    }
                })
            },
            save() {
                var that = this
                this.$refs['judgeForm'].validate((valid) => {
                    if (valid) {  // 表单校验合法
                        let formData = new FormData();
                        if (this.imgData == null && this.imgUrl == '') {
                            that.$message.error("请先上传证件照")
                            return
                        }
                        const param = {
                            "raceId": this.raceId,
                            "idcard": this.ruleForm.idcard
                        }
                        this.request.post("/judge/queryInfo", param).then(async resp => {
                            if (resp.code === 200) {
                                this.$confirm('检测到您已存在报名信息，是否更新？', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning'
                                }).then(async () => {
                                    //存入id
                                    this.ruleForm.raceId = this.raceId
                                    if (this.imgData && this.imgUrl == '') {
                                        formData.append('file', this.imgData, this.ruleForm.idcard + '.png');
                                        await that.request.post("/file/upload", formData).then(res => {
                                            if (res.code == 200) {
                                                that.ruleForm.avatar = res.data.imgUrl
                                            } else {
                                                that.$message.error("头像更新失败")
                                            }
                                        })
                                    } else {
                                        that.ruleForm.avatar = this.imgUrl
                                    }
                                    await this.request.post("/judge/save", this.ruleForm).then(res => {
                                        if (res.code === 200) {
                                            that.$alert("更新成功！请等待审核")
                                            that.$refs['judgeForm'].resetFields()
                                            setTimeout(function () {
                                                location.reload()
                                            },1500)
                                        } else {
                                            this.$message.error(res.message)
                                        }
                                    })
                                }).catch(() => {
                                    this.$message({
                                        type: 'info',
                                        message: '已取消'
                                    });
                                });
                            } else {
                                //存入id
                                this.ruleForm.raceId = this.raceId
                                if (this.imgData && this.imgUrl == '') {
                                    formData.append('file', this.imgData, this.ruleForm.idcard + '.png');
                                    await that.request.post("/file/upload", formData).then(res => {
                                        if (res.code == 200) {
                                            that.ruleForm.avatar = res.data.imgUrl
                                        } else {
                                            that.$message.error("头像更新失败")
                                        }
                                    })
                                } else {
                                    that.ruleForm.avatar = this.imgUrl
                                }


                                await this.request.post("/judge/save", this.ruleForm).then(res => {
                                    if (res.code === 200) {
                                        that.$alert("报名成功，请等待审核")
                                        that.$refs['judgeForm'].resetFields()
                                        setTimeout(function () {
                                            location.reload()
                                        },3000)

                                    } else {
                                        this.$message.error(res.message)
                                    }
                                })
                            }
                        })
                    }
                });
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = val
            },
            handleSizeChange(pageSize) {
                console.log(pageSize)
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                console.log(pageNum)
                this.pageNum = pageNum
                this.load()
            },
            handleFileUploadSuccess(res) {
                this.form.file = res
            },
            handleImgUploadSuccess(res) {
                this.form.img = res
            }
        }
    }
</script>
<style>

    .bg {
        width: 100%;
        height: 100vh;
        overflow-y: auto;
        background: #f5f5f5;
        /*background: url("../assets/imgs/p2.png");*/
        background-size: 100% 100%;
    }

    .el-form-item {
        width: 100%;
        display: flex;
        flex-direction: column;
    }

    .el-form-item__label {
        width: 100%;
        color: #fff;
        font-weight: bold;
    }

    .el-dialog {
        margin-top: 4vh;
    }

    .h3 {
        text-align: center;
        color: #F56C6C;
    }

    .Tkcontent {
        width: 1000px;
        margin: 40px auto;

        /*background: rgb(255,255,255,.5);*/
        background: rgb(45, 39, 19, 0.9);
        /* padding:50px 0; */
        padding: 50px 0;
    }

    .TKfooter {
        text-align: center;
    }

    .TKfooter .el-button {
        width: calc(100% - 100px);
    }

    .TKform {
        width: 100%;
        padding: 20px 50px;
    }

    @media (max-width: 768px) {
        body {
            background: #fff;
        }

        .Tkcontent {
            width: 100%;
            margin: 0;
            padding: 20px 0;

        }

        .TKform {
            width: 100%;
            padding: 20px;
        }

        .TKfooter .el-button {
            width: calc(100% - 40px);
        }
    }
    @media screen and (max-width: 768px) {
        .el-message-box {
            width:80% !important;
        }
    }
</style>